<template>
	<view class="container">
		<u-navbar  placeholder="true"  title="实名举报" titleStyle="color:white;font-weight:bold" :bgColor="background">
			<view class="slot-wrap" slot="left">
				<u-icon name="home"  color="white" size="40" @click="returnHome"></u-icon>
			</view>
		</u-navbar>
		<view class="reportUser">
			<view class="titleContainer">
				<text class="title">基本信息</text>
			</view>
			<view class="userForm">
				<u--form 
					:model="reportUser" 
					ref="uFormUser"
					:rules="rulesUser"
					labelWidth="78px"
				>
						<u-form-item  
							label="姓名"
							borderBottom
							prop="name"
							required
						>
							<u-input  v-model="reportUser.name" placeholder="请输入您的姓名" customStyle="width:1000px"   border="none"></u-input>
						</u-form-item>	
						<u-form-item  
							label="手机号码" 
							borderBottom
							prop="phone"
							required
						>
							<u-input  v-model="reportUser.phone" placeholder="请输入您的手机号码" customStyle="width:1000px"   border="none" @change="changeTel"></u-input>						
						</u-form-item>
						<u-form-item  
							label="性别" 
							borderBottom
							prop="sex"
							required
						>
							<u-input v-model="reportUser.sexName" placeholder="请选择性别" customStyle="width:1000px"   border="none" @focus="showSexType = true"></u-input>
							<u-picker  :show="showSexType" :columns="ListSex" keyName="label" @confirm="confirmSexType" @cancel="cancelSexType"></u-picker>
						</u-form-item>
						<u-form-item  
							label="邮箱" 
							borderBottom
							prop="email"
							required
						>
					       <u-input v-model="reportUser.email" placeholder="请输入您的邮箱地址" customStyle="width:1000px"   border="none"></u-input>
						</u-form-item>
						<u-form-item  
						    label="所在省" 
							borderBottom
							prop="provinceName"
							required
						>
							<u-input  
								v-model="reportUser.provinceName" 
								placeholder="省/直辖市" 
								border="none" 
								@focus="showProvince= true;"
							>
							</u-input>
							<u-picker 
								:show="showProvince"
								ref="uPicker" 
								:columns="columnsProvince"
								keyName="value"
								@confirm="confirmProvince" 
								@cancel="cancelProvince"
							>
							</u-picker>
							</u-form-item>
							<u-form-item
								label="所在市"
								borderBottom
								prop="cityName"
								required
							>
								<u-input
									v-model="reportUser.cityName" 
									placeholder="市"   
									border="none" 
									@focus="showCity = true;"
								>
								</u-input>
								<u-picker 
									:show="showCity"
									ref="uPickerCity" 
									:columns="columnsCity"	
									keyName="value"
									@confirm="confirmCity" 
									@cancel="cancelCity"
								>
								</u-picker>
							</u-form-item>
							<u-form-item
									label="所在区"
									borderBottom
									prop="countryName"
									required
							>
							<u-input
								v-model="reportUser.countryName" 
								placeholder="区/县"   
								border="none" 
								@focus="showCountry = true;"
							>
							</u-input>
							<u-picker 
								:show="showCountry"
								ref="uPickerCountry" 
								:columns="columnsCountry"	
								keyName="value"
								@confirm="confirmCountry" 
								@cancel="cancelCountry"
							>
							</u-picker>
						</u-form-item>
						<u-form-item
							label="验证码"
							borderBottom
							prop="code"
							required
						>
							<u-input v-model="reportUser.code" placeholder="请输入短信验证码"  border="none">
								<template slot="suffix">
									<u-code
										ref="uCode"
										@change="codeChange"
										seconds="60"
										changeText="60秒后重新获取"
									>
									</u-code>
									<u-button
										@click="getCode"
										:text="tips"
										type="success"
										size="mini"
										:disabled="this.disabled"
									>
									</u-button>
								</template>
							</u-input>
						</u-form-item>
					</u--form>
				</view>
		</view>
		<view class="reportInfo">
			<view class="titleContainer">
				<text class="title">举报信息</text>
			</view>
			<view class="userForm">
				<u-notice-bar :text="textNotice" mode="closable"></u-notice-bar>
				<u--form 
					:model="form" 
					ref="uForm"
					:rules="rules"
					labelWidth="78px"
				>
						<u-form-item  
							label="危害类型"
							borderBottom
							prop="harmTypeName"
							required
						>
							<u-input  v-model="form.harmTypeName" placeholder="请选择举报内容的危害类型" customStyle="width:1000px"   border="none" @focus="show = true;"></u-input>
		                    <u-picker  :show="show" :columns="List" keyName="label" @confirm="confirmHarmType" @cancel="cancelHarmType"></u-picker>
						</u-form-item>	
						<u-form-item  
							label="举报类型" 
							borderBottom
							prop="reportedTypeName"
							required
						>
							<u-input  v-model="form.reportedTypeName" placeholder="请选择举报内容的载体" customStyle="width:1000px"   border="none" @focus="showReportedType = true;"></u-input>
							<u-picker  :show="showReportedType" :columns="ListReportedType" keyName="label" @confirm="confirmReportedType" @cancel="cancelReportedType"></u-picker>
						</u-form-item>
						<u-form-item  
							label="网站名称" 
							borderBottom
							prop="name"
							required
						>
							<u-input v-model="form.name" placeholder="请输入网站名称" customStyle="width:1000px"   border="none"></u-input>
						</u-form-item>
						<u-form-item  
							label="详细网址" 
							borderBottom
							prop="extraContent"
							required
						>
					       <u-input v-model="form.extraContent" placeholder="请输入详细网址" customStyle="width:1000px"   border="none"></u-input>
						</u-form-item>
						<u-form-item  
						    label="详细内容" 
							borderBottom
							prop="reportContent"
							required
						>
							<u--textarea 
								v-model="form.reportContent" 
								placeholder="请输入详细内容" 
								border="surround" 
								maxlength="-1"
								height="250"
							>
							</u--textarea>
						</u-form-item>
						<u-form-item  
							label="附件" 
						>
							<u-upload
							    maxSize="10*1024*1024"
								:previewFullImage="true"
								:fileList="fileList"
								@afterRead="afterRead"
								@delete="deletePic"
								multiple
								:maxCount="10"
								width="250" 
								height="250"
							>
							</u-upload>
						</u-form-item>
						<u-form-item
							label="验证码"
							borderBottom
							prop="code"
							required
						>
							<u-input v-model="form.code" placeholder="请输入验证码"  border="none">
								<template slot="suffix">
									<u--image :showLoading="true" :src="src" width="99px" height="27px" @click="click"></u--image>
								</template>
							</u-input>
						</u-form-item>
					</u--form>
					<u-button type="primary" size="large" text="提 交" @click="submit"></u-button>
			</view>
		</view>
	</view>
</template>

<script>
	import {HARM_TYPE_LIST,REPORT_TYPE_LIST,USER_SEX_TYPE} from '@/utils/constant.js'
	import {get_province,get_city,get_area,code_2_name} from '@/utils/area.js'
	export default {
		data() {
			return {
				tips: '',
				src:'',
				columnsProvince: [],
				columnsCity:[],
				columnsCountry:[],
				disabled:true,
				show:false,
				showProvince:false,
				showCity:false,
				showCountry:false,
				showSexType:false,
				showReportedType:false,
				reportUser:{
					name:'',
					phone:'',
					sexName:'',
					sex:1,
					email:'',
					provinceName:'',
					provinceCode:'',
					cityName:'',
					cityCode:'',
				    countryName:'',
					countryCode:'',
					token:''
				},
				form:{
				  harmTypeName:'',
				  harmType:'',
				  reportedTypeName:'',
				  reportedType:'',
				  name:'',
				  extraContent:'',
				  reportContent:'',
				  fileIds:[],
				  code:'',
				  key:''
				},
				List:[HARM_TYPE_LIST],
				ListReportedType:[REPORT_TYPE_LIST],
				ListSex:[USER_SEX_TYPE],
				background: '#24A7FE',	
				fileList:[],
				fileIds:[],
				textNotice:'上传的附件总大小不能超过100M，总数量不能超过10个，单个附件大小不能超过10M',
				rulesUser:{
					name:[
						{
							required: true,
							message: '请输入姓名',
							trigger: 'blur'
						}
					],
					phone:[
						{
							required: true,
							message: '请输入手机号码',
							trigger:'blur'
						},
						{							required: true,							pattern: /^[1][3,4,5,7,8,9][0-9]{9}$/,							message: '请输入正确的手机号码',							trigger: ['blur', 'change'],                        }
					],
					sex:[
						{
							required: true,
							message: '请选择性别'
						}
					],
					email:[
						{
							required: true,
							message: '请输入邮箱',
							trigger:'blur'
						},
						{
							required: true,
							transform(value) {
								return String(value);
							},
							pattern: /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,
							message: '请输入正确的邮箱',
							trigger: ['blur', 'change'],
						}
					],
					provinceName:[
						{
							required: true,
							message: '请选择所在省/直辖市'
						}
					],
					cityName:[
						{
							required: true,
							message: '请选择所在市'
						}
					],
					countryName:[
						{
							required: true,
							message: '请选择所在区/县'
						}
					],
					code:[	
						{
							required: true,
							message: '请输入手机验证码',
							trigger:'blur'
						}
					]
				},
				rules:{
					harmTypeName:[
						{
							required: true,
							message: '请选择危害类型'
						}
					],
					reportedTypeName:[
						{
							required: true,
							message: '请选择举报内容的载体'
						}
					],
					name:[
						{
							required: true,
							message: '请输入网站名称',
							trigger: 'blur'
						}
					],
					extraContent:[
						{
							required: true,
							message: '请输入详细网址',
							trigger: 'blur'
						}
					],
					reportContent:[
						{
							required: true,
							message: '请输入详细内容',
							trigger: 'blur'
						}
					],
				    code:[
						{
							required: true,
							message: '请输入验证码',
							trigger: ['change','blur']
						},
						{
							type:'number',
							message:'验证码必须为右图中计算数值结果',
							trigger:['change','blur']
						}
					]
				}
			};
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
			this.$refs.uFormUser.setRules(this.rulesUser);
		},
		onLoad() {
			this.getGraphic()
			this.initProvince()
		},
		onShow() {
			console.log('Index page show');
			this.getGraphic()
			this.initProvince()
		},
		methods:{
			initProvince(){
				this.columnsProvince=[get_province()]
			},
			initCity(provinceCode,provinceName){
				this.columnsCity=[get_city(provinceCode,provinceName)]
			},
			initCountry(provinceCode,provinceName,cityCode,cityName){
				this.columnsCountry=[get_area(provinceCode,provinceName,cityCode,cityName)]
			},
			returnHome(){
				uni.navigateTo({
					url:'/pages/index/index'
				})
			},
		    async getGraphic(){
				const res = await this.$api.verificatonCode.graphicVerificationCode()
				console.log(res);
				if(res.data.success===true){
					this.src=res.data.data.codeUrl
					this.form.key=res.data.data.key
				}
				console.log(this.src);
				console.log(this.form.key);
			},
			confirmProvince(e){
			    this.reportUser.provinceName= e.value[0].value;
				this.reportUser.provinceCode= e.value[0].code;
				this.showProvince = false
				this.initCity(this.reportUser.provinceCode,this.reportUser.provinceName)
				console.log(this.columnsCity)
			},
			cancelProvince(){
				this.reportUser.provinceName= '';
				this.reportUser.provinceCode= '';
				this.showProvince = false
			},
			confirmCity(e){
			    this.reportUser.cityName= e.value[0].value;
				this.reportUser.cityCode= e.value[0].code;
				this.showCity = false
				this.initCountry(this.reportUser.provinceCode,this.reportUser.provinceName,this.reportUser.cityCode,this.reportUser.cityName)
			},
			cancelCity(){
				this.reportUser.cityName= '';
				this.reportUser.cityCode= '';
				if(this.reportUser.provinceName===''){
					this.columnsCity=[];
				}
				this.showCity = false
			},
			confirmCountry(e){
				this.reportUser.countryName= e.value[0].value;
				this.reportUser.countryCode= e.value[0].code;
				this.showCountry=false
			},
			cancelCountry(){
				this.reportUser.countryName= '';
				this.reportUser.countryCode= '';
				if(this.reportUser.cityName===''){
					this.columnsCountry=[];
				}
				this.showCountry=false
			},
			confirmSexType(e){
				this.reportUser.sexName= e.value[0].label;
				this.reportUser.sex= e.value[0].value;
				this.showSexType = false;
			},
			cancelSexType(){
				this.reportUser.sexName= '';
				this.reportUser.sex= '';
				this.showSexType = false;
			},
			confirmHarmType(e) {
				this.form.harmTypeName = e.value[0].label;
				this.form.harmType=e.value[0].value;
				this.show= false;
			},
			cancelHarmType(){
				this.form.harmTypeName='';
				this.form.harmType='';
				this.show=false;
			},
			confirmReportedType(e){
				this.form.reportedTypeName=e.value[0].label;
				this.form.reportedType=e.value[0].value;
				this.showReportedType=false;
			},
			cancelReportedType(){
				this.form.reportedTypeName='';
				this.form.reportedType='';
				this.showReportedType=false;
			},

			deletePic(event){
				this[`fileList${event.name}`].splice(event.index, 1)
				console.log(this.fileList);
			},
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
				console.log(this.fileList);
				},
				uploadFilePromise(url) {
					return new Promise((resolve, reject) => {
						let a = uni.uploadFile({
							url: 'https://www.hn12377.gov.cn/api/material/upload', //文件服务器地址
							filePath: url,
							name: 'file',
							success: (res) => {
								res.data=JSON.parse(res.data)
								setTimeout(() => {
									resolve(res.data)
								}, 1000)
								console.log(res.data);
							}
						});
					})
				},
				click(){
					this.getGraphic()
				},
				codeChange(text) {
					this.tips = text;
				},
				changeTel(){
				    const res =this.$refs.uFormUser.validateField('phone',(error) => {
						console.log(error);
						if(error.length===0){
							console.log('校验成功');
							this.disabled = false
						}else{
							console.log('校验失败');
							this.disabled = true
						}
					})
				},
			    getCode() {
					if (this.$refs.uCode.canGetCode) {
					   const res =  this.$api.verificatonCode.mobileVerificationCodeByReal(this.reportUser.phone) 
					   console.log(res)
					   // 模拟向后端请求验证码
					   uni.showLoading({
							title: '正在获取验证码'
					   })
					   setTimeout(() => {
							uni.hideLoading();
							// 这里此提示会被this.start()方法中的提示覆盖
							uni.$u.toast('验证码已发送');
							// 通知验证码组件内部开始倒计时
							this.$refs.uCode.start();
					   }, 2000);
					} else {
					  uni.$u.toast('倒计时结束后再发送');
					}
				},
				submit(){
					console.log(this.fileList);
					for(let i=0;i<this.fileList.length;i++){
						this.fileIds.push(this.fileList[i].url.data.materialId)
					}
					console.log(this.fileIds);
					let submitForm={
						code:this.form.code,
						key:this.form.key,
						fileIds:this.fileIds,
						reportInfo:{
							harmType:this.form.harmType,
							reportedType:this.form.reportedType,
							platformId:1, //这个字段暂时搞不清楚什么意思
							name:this.form.name,
							webAddress:'',
							extraContent:this.form.extraContent,
							reportContent:this.form.reportContent,
							reporterId:'',
							reporterName:'',
							reporterSex:this.reportUser.sex,
							reporterPhone:'',
							reporterEmail:''
						},
						reportUser:{
							cityCode: this.reportUser.cityCode,
							countryCode: this.reportUser.countryCode,
							email: this.reportUser.email,
							name: this.reportUser.name,
							phone: this.reportUser.phone,
							provinceCode: this.reportUser.provinceCode,
							sex: this.reportUser.sex,
							token: ""
						}
					}
				   this.$refs.uFormUser.validate().then(res => {
				   	 this.$refs.uForm.validate().then(res=>{
						 this.$api.report.realUserReport(submitForm,this.form.code,this.form.key).then(res=>{
						    console.log(res);
						    if(res.data.success===true){
						 	   this.fileList=[]
						 	   this.fileIds=[]
						 	   uni.showModal({
						 		title: '举报成功',
						 		content:'举报编号为'+res.data.data,
						 		confirmText:'点击查询',
						 		success:function (res) {
						 			if (res.confirm) {
						 				console.log('用户点击确定');
						 				uni.switchTab({
						 					url:'/pages/select/select'
						 				})
						 			} else if (res.cancel) {
						 				console.log('用户点击取消');
						 			}
						 								}
						 	   })
						    }else{
						 	   this.fileList=[]
						 	   this.fileIds=[]
						 	   uni.showToast({
						 		title: '举报失败',
						 		//将值设置为 success 或者直接不用写icon这个参数
						 		icon: 'error',
						 		//显示持续时间为 2秒
						 		duration: 2000
						 	   })
						 	   this.$refs.uForm.resetFields()
						 	   this.$refs.uFormUser.resetFields()
						    }
						 })
					 }).catch(errors =>{
						 uni.$u.toast('表单校验失败，请检查举报信息表单重新填写')
					 })
				   }).catch(errors => {
				   	uni.$u.toast('表单校验失败，请检查基本信息表单重新填写')
				   })
				}
		}
	}
</script>

<style scoped lang="scss">
.container{
	*{
		margin-bottom: 10rpx;
	}
		.slot-wrap{
			display: flex;
			align-items: center;
			margin-bottom: 0;
			      }
		.reportUser{
			.titleContainer{
				border-bottom: 1px solid lightgrey;
				padding-bottom: 7px;
				margin: 7px 18px;
				.title{
					font-weight: bold;
					width: 96px;
					height: 33px;
					color: rgba(16, 16, 16, 1);
					font-size: 24px;
					text-align: left;
					font-family: PingFangSC-regular;
				}
			}
			.userForm{
				margin: 7px 18px;
			}
		}
		.reportInfo{
			.titleContainer{
				border-bottom: 1px solid lightgrey;
				padding-bottom: 7px;
				margin: 7px 18px;
				.title{
					font-weight: bold;
					width: 96px;
					height: 33px;
					color: rgba(16, 16, 16, 1);
					font-size: 24px;
					text-align: left;
					font-family: PingFangSC-regular;
				}
			}
			.userForm{
				margin: 7px 18px;
			}
		}
	}
</style>
